package com.ucap.weking.guangan.tools;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;

import com.google.gson.Gson;
import com.ucap.weking.guangan.bean.VersionBean;
import com.ucap.weking.guangan.dataUri.DataUri;
import com.ucap.weking.guangan.dialog.VersionInfoDialog;
import com.ucap.weking.guangan.httpTools.HttpCallRequest;
import com.ucap.weking.guangan.views.MyToast;

/**
 * Created by weking on 2017/11/9.
 * 版本检测工具
 */

public class VersionTestingTools {
    /**
     * 版本检测
     *
     * @param act 当前activity对象
     */
    public static void testingVersion(Activity act, boolean isVersonNew) {
        if (isVersonNew)
            MyToast.showTrue(act, "正在检测新版本...");
        getNewsVersionCode(act, isVersonNew);

    }

    private static VersionBean getNewsVersionCode(final Activity act, final boolean isVersionNew) {
        final VersionBean[] versionBean = new VersionBean[1];
        HttpCallRequest.callRequest(DataUri.getVERSION(), new HttpCallRequest.OnCallListener() {
            @Override
            public void onRequest(final String body) {
                act.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (!body.equals("")) {
                            Gson gson = new Gson();
                            versionBean[0] = gson.fromJson(body, VersionBean.class);
                            try {
                                PackageInfo packageInfo = act.getPackageManager().getPackageInfo(act.getPackageName(), 0);
                                if (packageInfo.versionCode < versionBean[0].getVersionCode()) {//服务器版本大于本地版本
                                    VersionInfoDialog.showDialog(act, versionBean[0].getVersionContent(), versionBean[0].getVersionUri());
                                } else {
                                    if (isVersionNew)
                                        MyToast.showTrue(act, "已是最新版");
                                }
                            } catch (PackageManager.NameNotFoundException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });

            }

            @Override
            public void onErr(Exception e) {
                act.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        MyToast.showTrue(act, "连接失败！");
                    }
                });
            }
        });
        return versionBean[0];
    }
}
